<template>
  <div>
    <breadcrumb></breadcrumb>

    <!-- 列表 -->
    <div class="main">
      <div class="main_head">
        <div class="main_head_left">
          已选择<span style="color: #1890ff">2</span>项
        </div>
        <div class="main_head_right">
          <button class="addCargoOwner" @click="showRoleDialog('新增角色')">
            <i class="el-icon-plus iconBtn"></i>
            <span>新增</span>
          </button>
          <button class="addCargoOwner" @click="delectRole()">
            <i class="iconfont icon-lajitong iconBtn"></i>
            <span>删除</span>
          </button>
        </div>
      </div>
      <div class="list">
        <el-table :data="records" style="width: 100%" @selection-change="handleSelectionChange" header-align="left" ref="table">
          <el-table-column align="left" type="selection" width="50"></el-table-column>
          <el-table-column align="left" prop="SerialNumber" width="80" label="序号">
          </el-table-column>
          <el-table-column align="left" prop="roleName" label="角色"></el-table-column>
          <el-table-column align="left" prop="remark" label="备注">
          </el-table-column>
          <el-table-column align="left" prop="createBy" label="操作人">
          </el-table-column>

          <el-table-column align="left" prop="createTime" label="操作时间" width="160px">
          </el-table-column>
          <el-table-column align="left" label="操作" width="153">
            <template slot-scope="scope">
              <div>
                <!-- <el-button type="text" size="small" @click="showPermissionDialog()">权限设置</el-button> -->
                <el-button type="text" size="small" @click="showRoleDialog('编辑角色', scope.row.roleId)">编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="paginationBox">
        <el-pagination class="pagination" background layout="slot,prev, pager, next" :total="data.total * 1"
          :page-size="data.size * 1" :pager-count="5" @current-change="changePages($event)">
          <template slot>
            <span style="
                color: #686868;
                font-size: 12px;
                margin-right: 20px;
                display: inline-block;
              ">共{{ data.total }}条,每页{{ data.size }}条</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog class="dialog" :title="dialogTitle" :visible.sync="visibleAddBox" width="558px"
      :before-close="handleClose">
      <el-form ref="addRoleForm" :model="addRoleForm" :rules="addRoleRules" label-width="70px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称" prop="roleName" class="roleSelectBox">
              <el-input size="small" v-model="addRoleForm.roleName"></el-input>

              <!-- <el-select v-model="addRoleForm.roleId" filterable placeholder="请选择" style="width: 100%">
                <el-option v-for="item in RoleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId">
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="权限字符" prop="roleKey" class="roleSelectBox">
              <el-input size="small" v-model="addRoleForm.roleKey"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色顺序" prop="roleSort" class="roleSelectBox">
              <el-input-number size="small" v-model="addRoleForm.roleSort" controls-position="right"
                @change="handleChange" :min="1" :max="10"></el-input-number>
            </el-form-item>
          </el-col> -->
          <!-- 角色状态(1停用 0正常) -->
          <el-col :span="24">
            <el-form-item label="状态" class="roleSelectBox">
              <div class="statusBox" style="display: flex;align-items: center;height:36px">
                <el-radio v-model="addRoleForm.status" label="0">正常</el-radio>
                <el-radio v-model="addRoleForm.status" label="1">停用</el-radio>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单权限" class="roleSelectBox">
              <div class="menuBox">
                <div class="checkbox">
                  <el-checkbox-group v-model="checkList" @change="controlChange">
                    <el-checkbox label="展开/折叠"></el-checkbox>
                    <el-checkbox label="全选/全不选"></el-checkbox>
                  </el-checkbox-group>
                </div>
                <div class="selectBg">
                  <el-tree ref="tree" :data="authorityArr" show-checkbox node-key="id" :default-expanded-keys="[2, 3]"
                    :default-checked-keys="[5]" props="label" @check-change="treeChange" :check-strictly="checkStrictly">
                  </el-tree>
                </div>

              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" class="notes">
              <el-input v-model="addRoleForm.remark" resize="none" :rows="2" type="textarea" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="display: flex; justify-content: flex-end">
            <el-button class="cancelBtn" @click="visibleAddBox = false">取 消</el-button>
            <el-button class="submitBtn" type="primary" @click="addSubmitRole('addRoleForm')">确 定</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
import breadcrumb from "@/components/breadcrumb.vue";
import router from "@/router";
import httpApi from "@/http";



export default {


  data() {
    // 检查 项目名称 是否重复
    let checkRoleName = (rule, value, callback) => {
      let params = {};
      console.log(this.ownerId != "")
      if (this.contractId != "") {
        params = {
          projectName: this.addContractForm.projectName,
          contactId: this.contractId,

        };
        console.log(params)
      } else {
        params = {
          projectName: this.addContractForm.projectName,


        };
      }
      //console.log('传参', params);
      httpApi.selfOperatedSettingsApi.checkProjectName(params).then((res) => {
        //console.log('校验', res);
        if (res.data.code == 200) {
          callback(); //通过不传值
        } else if (res.data.code == 202) {
          callback(new Error("项目名称已存在")); //callback()传了参数字段就代表校验不通过
        }
      });
    };
    return {
      checkStrictly: false,
      dialogTitle: "",
      loading: false,

      checkList: [],
      records: [],
      data: {},
      enterpriseName: "", //企业名称 值
      visibleAddBox: false,
      visiblePermissionBox: false,
      pageSize: "10",
      pageCurrent: 1,


      RoleOptions: [],

      addRoleForm: {
        roleName: "",//角色名称
        remark: "",//备注
        // roleKey: '',//权限字符
        // roleSort: "",
        menuIds: [],
        status: "0",
        useType: "1" //使用类型
      },
      addRoleRules: {
        roleName: [
          { required: true, message: "请输入", trigger: "change" },
          // {
          //   message: "该项目名称已存在",
          //   validator: checkRoleName,
          //   trigger: "blur",
          // }
        ],
        remark: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        // roleKey: [
        //   { required: true, message: "请输入", trigger: "blur" },
        // ],
      },

      isIndeterminate: true,


      multipleSelection: [], //删除 选项数组
      PermissionRouteData: [],


      //权限选项数组
      authorityArr: [],
    };
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();    //初始值不为空 清空 暂 自己循环清空
      this.addRoleForm.roleName = ''
      this.addRoleForm.remark = ''
      this.addRoleForm.menuIds = []
      this.addRoleForm.status = '0'
      this.addRoleForm.useType = '1'

    },
    // 合同 弹窗关闭之前
    handleClose() {
      if (this.ContractTitle == '编辑角色') {
        this.resetForm('addRoleForm')
      } else if (this.ContractTitle == '新增角色') {
        this.resetForm('addRoleForm')
        // sessionStorage.setItem('RoleForm', JSON.stringify(this.addRoleForm))
      }
      this.visibleAddBox = false

    },
    changePages(val) {
      this.pageCurrent = val
      this.getList()
    },
    treeChange(val, b, c) {

    },
    controlChange(val) {
      console.log(val)

      if (val.includes("全选/全不选")) {
        this.allChecked()
      } else {
        this.resetChecked()
      }

      if (val.includes("展开/折叠")) {
        let treeNodeList = this.$refs.tree.store._getAllNodes();

        for (var i = 0; i < treeNodeList.length; i++) {
          treeNodeList[i].expanded = true;
        }
      } else {
        let treeNodeList = this.$refs.tree.store._getAllNodes();

        for (var i = 0; i < treeNodeList.length; i++) {
          treeNodeList[i].expanded = false;
        }
      }


    },

    // 菜单权限全选方法
    allChecked() {


      let nodeArr = []

      this.authorityArr.forEach(item => {
        nodeArr.push(item.id)
      })
      console.log(nodeArr)

      this.$refs.tree.setCheckedKeys(nodeArr);
    },
    // 菜单权限  清空
    resetChecked() {
      // 将选中设置为空
      this.$refs.tree.setCheckedKeys([]);
    },

    handleChange(value) {
      console.log(value)
      this.addRoleForm.num = value
    },
    getList() {
      let params = {
        current: this.pageCurrent,
        size: this.pageSize,

      };
      // console.log(params);
      httpApi.basicSettingApi.getRoleList(params).then((res) => {
        // console.log("列表", res);
        this.records = res.data.data.records;

        this.data = res.data.data;
        // 前端解决序号
        this.records.forEach((item, i) => {
          let num = i + 1 + Number(this.pageSize) * (this.pageCurrent - 1);
          item.SerialNumber = num
        });
        // console.log(res.data.data.records);
      });
    },
    showRoleDialog(title, roleId) {
      this.getPermissionData();//权限数据
      this.dialogTitle = title
      this.visibleAddBox = true

      if (this.dialogTitle == '编辑角色') {
        this.checkStrictly = true
        this.addRoleForm.roleId = roleId
        // 获取编辑回填数据
        let params = {
          roleId: roleId,
          useType: '1'
        }

        httpApi.basicSettingApi.getEditRoleData({ roleId }).then(res => {

          if (res.data.code == 200) {
            this.addRoleForm.status = res.data.data.status
            this.addRoleForm.roleName = res.data.data.roleName
            this.addRoleForm.remark = res.data.data.remark

            this.addRoleForm.menuIds = []
            httpApi.basicSettingApi.getEditRoleMenu(params).then(res => {
              console.log(res);
              if (res.data.code == 200) {
                console.log('权限菜单id回填', res.data.checkedKeys)
                // this.addRoleForm.menuIds = res.data.checkedKeys


                this.$refs.tree.setCheckedKeys(res.data.checkedKeys)
                this.checkStrictly = false


              }
            })
          }
        })
      } else if (this.dialogTitle == '新增角色') {
        delete this.addRoleForm.roleId
        // this.addRoleForm.menuIds=["1681506000415444993","1681506477249089538"]
      }
    },
    addSubmitRole(formName) {

      if (this.loading == true) {

        return
      }
      this.loading = true
      this.addRoleForm.menuIds = [] //清空权限数组
      // 获取被选中的节点, 遍历获取  id数据装入表单

      this.$refs.tree.getCheckedNodes(false, true).forEach(item => {
        this.addRoleForm.menuIds.push(item.id)
      })

      console.log(this.addRoleForm.menuIds);

      if (this.dialogTitle == '新增角色') {
        console.log(this.addRoleForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            httpApi.basicSettingApi.addRole(this.addRoleForm).then(res => {
              if (res.data.code == 200) {
                // this.getRoleOptions()
                this.$message.success('新增角色成功')
                this.getList(); //角色列表
                this.visibleAddBox = false

              }
            })
          } else {
            this.$message.error('请填写完整信息')
            return false;
          }
        });
        this.loading = false

      } else if (this.dialogTitle == '编辑角色') {

        console.log(this.addRoleForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {

            httpApi.basicSettingApi.editRole(this.addRoleForm).then(res => {
              if (res.data.code == 200) {
                // this.getRoleOptions()
                this.$message.success('编辑角色成功')
                this.getList(); //角色列表
                this.visibleAddBox = false
              }
            })
          } else {
            this.$message.error('请填写完整信息')
            return false;
          }
        });
        this.loading = false

      }
    },
    handleSelectionChange(val) {
      let roleIdArr = [];
      val.forEach((item) => {
        roleIdArr.push(item.roleId);
      });
      this.multipleSelection = roleIdArr.join(',')
      console.log(this.multipleSelection);

    },

    async getPermissionData() {

      // console.log(PermissionData);
      let res = await httpApi.basicSettingApi.getAuthorityOption()
      if (res.data.code == 200) {
        this.authorityArr = res.data.data
        console.log(this.authorityArr)
      }

    },




    // 全选

    handleCheckAllChange(val) {
      // console.log(val);
      this.checkedCities = val ? PermissionData : [];
      this.isIndeterminate = false;
    },

    //删除角色
    delectRole() {
      this.$confirm('此操作将永久删除已选择的角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length == 0) {
          this.$message.warning('请先选择角色')
          return
        }
        let params = {
          roleIds: this.multipleSelection
        }
        httpApi.basicSettingApi.DeleteRole(params).then(res => {
          if (res.data.code == 200) {
            this.$message.success('删除角色成功')
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });



    },
    // 获取所有角色选项
    getRoleOptions() {
      httpApi.basicSettingApi.getRoleSelection().then(res => {
        if (res.data.code == 200) {
          this.RoleOptions = res.data.data
        }

      })
    },
    // 记录滚动距离
    scrollEvent(res) {
      this.$route.meta.scrollTop = res.target.scrollTop
    },



  },

  created() {
    // this.getPermissionData();//权限数据
    this.getRoleOptions() //角色选项
    this.getList(); //角色列表
  },
  mounted() {


  },
  activated() {
    //组件激活时监听表格滚动条位置,
    this.$refs.table.bodyWrapper.addEventListener('scroll', this.scrollEvent, false)
    // 激活设置滚动位置
    this.$refs.table.bodyWrapper.scrollTop = this.$route.meta.scrollTop
  },
  beforeRouteLeave(to, from, next) {
    // 为了节省资源，再离开页面的时候关闭对于scroll事件的监听
    this.$refs.table.bodyWrapper.removeEventListener('scroll', this.scrollEvent)
    next()
  },


  components: {
    breadcrumb,
  },
};
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: calc(100vh - 127px);
  background-color: #fff;

  .main_head {
    display: flex;
    justify-content: space-between;
    height: 64px;
    align-items: center;
    padding: 0 30px;

    .main_head_left {
      font-size: 12px;
      color: #262626;
    }

    .main_head_right {
      .addCargoOwner {
        background-color: #1890ff;
        border-radius: 4px;
        height: 32px;
        color: #ffffff;
        font-size: 12px;
        padding: 8px 17px 9px 17px;
        transition: 0.2s;
        cursor: pointer;
        margin-right: 17px;

        .iconBtn {
          margin-right: 7px;
          font-size: 12px;
        }

        &:hover {
          opacity: 0.8;
        }
      }
    }
  }

  .list {
    height: calc(100% - 112px);
    padding: 0 30px;

    ::v-deep .el-table__body-wrapper {
      height: calc(100vh - 286px) !important;
      overflow-y: scroll;
    }

    // 表头样式
    ::v-deep .el-table__header th {
      background-color: #f0f6fd;
      color: #262626;
      font-size: 12px;
      font-weight: bold;
      text-align: left;
      height: 48px;
      padding: 0;

      // 表 body的td
      ::v-deep .el-table__body td {
        color: #595959;
        font-size: 12px;
      }
    }


  }

  .paginationBox {
    border-top: 1px solid #f0f0f0;
    width: 100%;
    background-color: #fff;
    display: flex;
    height: 48px;
    padding: 0 30px;

    align-items: center;

    .pagination {
      margin-left: auto;
    }
  }
}

.dialog {

  .menuBox {
    .statusBox {
      height: 36px;
      display: flex;
      align-items: center;
    }

    .checkbox {
      height: 36px;
      line-height: 36px;
    }

    .selectBg {
      width: 400px;
      height: 300px;
      overflow-y: scroll;
    }


  }

  // 标题
  ::v-deep .el-dialog__header {
    border-bottom: 1px solid #f0f0f0;
    padding: 15px 20px;
    color: #262626;
    font-size: 14px;
    font-weight: bold;
    height: 50px;
  }

  ::v-deep .el-dialog__title {
    font-size: 14px;
    color: #303133;
    font-weight: bold;
  }

  //关闭图标
  ::v-deep .el-dialog__headerbtn .el-dialog__close {
    font-size: 15px;
  }

  ::v-deep .el-dialog__body {
    padding: 25px 40px 24px;
  }

  //   表格
  ::v-deep .el-form-item__label {
    line-height: 32px;
    font-size: 12px;
    color: #262626;
    // padding-top: 4px;
    width: 100%;
  }

  // ::v-deep .el-input__inner {
  //   line-height: 32px;
  //   height: 32px;
  //   padding: 0 10px;
  // }

  .cancelBtn {
    width: 80px;
    height: 36px;
    border: 1px solid #d9d9d9;
    color: #262626;
    font-size: 12px;
    border-radius: 4px;
    background-color: #fff;
  }

  .submitBtn {
    background-color: #1890ff;
    width: 80px;
    height: 36px;
    color: #fff;
    border-radius: 4px;
    font-size: 12px;
  }


  ::v-deep .el-input__icon {
    line-height: 0;
  }

  ::v-deep .el-form-item__content {
    line-height: 0;
  }

  .notes ::v-deep .el-textarea .el-input__count {
    bottom: 15px;
    color: #c0c4cc;
  }
}
</style>
